"""
健康模块测试用例
"""
from django.test import TestCase
from django.contrib.auth import get_user_model
from django.utils import timezone
from datetime import timedelta
from .models import HealthReport, BodyRecord, EatingRecord, SleepRecord, SportsRecord
from .views import user_health_stats, user_yesterday_analysis
from rest_framework.test import APIRequestFactory
from rest_framework import status

User = get_user_model()


class HealthReportModelTest(TestCase):
    """体检报告模型测试"""
    
    def setUp(self):
        self.user = User.objects.create_user(
            username='testuser',
            email='test@example.com',
            password='testpass123'
        )
    
    def test_create_health_report(self):
        """测试创建体检报告"""
        report = HealthReport.objects.create(
            user_id=self.user.id,
            file_path='test_report.pdf',
            analysis_result='测试分析结果',
            status='completed'
        )
        
        self.assertEqual(report.user_id, self.user.id)
        self.assertEqual(report.file_path, 'test_report.pdf')
        self.assertEqual(report.analysis_result, '测试分析结果')
        self.assertEqual(report.status, 'completed')


class HealthDataModelTest(TestCase):
    """健康数据模型测试"""
    
    def setUp(self):
        self.user = User.objects.create_user(
            username='testuser',
            email='test@example.com',
            password='testpass123'
        )
    
    def test_create_body_record(self):
        """测试创建身体指标记录"""
        record = BodyRecord.objects.create(
            user_id=self.user.id,
            height=175.5,
            weight=70.0,
            heart_rate=72
        )
        
        self.assertEqual(record.user_id, self.user.id)
        self.assertEqual(record.height, 175.5)
        self.assertEqual(record.weight, 70.0)
        self.assertEqual(record.heart_rate, 72)
    
    def test_create_eating_record(self):
        """测试创建饮食记录"""
        record = EatingRecord.objects.create(
            user_id=self.user.id,
            meal_type='breakfast',
            food_items='面包,牛奶,鸡蛋',
            calories=450
        )
        
        self.assertEqual(record.user_id, self.user.id)
        self.assertEqual(record.meal_type, 'breakfast')
        self.assertEqual(record.food_items, '面包,牛奶,鸡蛋')
        self.assertEqual(record.calories, 450)
    
    def test_create_sleep_record(self):
        """测试创建睡眠记录"""
        record = SleepRecord.objects.create(
            user_id=self.user.id,
            sleep_duration=7.5,
            sleep_quality=85
        )
        
        self.assertEqual(record.user_id, self.user.id)
        self.assertEqual(record.sleep_duration, 7.5)
        self.assertEqual(record.sleep_quality, 85)
    
    def test_create_sports_record(self):
        """测试创建运动记录"""
        record = SportsRecord.objects.create(
            user_id=self.user.id,
            sport_type='running',
            duration=30,
            calories_burned=300
        )
        
        self.assertEqual(record.user_id, self.user.id)
        self.assertEqual(record.sport_type, 'running')
        self.assertEqual(record.duration, 30)
        self.assertEqual(record.calories_burned, 300)


class HealthViewsTest(TestCase):
    """健康视图测试"""
    
    def setUp(self):
        self.factory = APIRequestFactory()
        self.user = User.objects.create_user(
            username='testuser',
            email='test@example.com',
            password='testpass123'
        )
        
        # 创建测试数据
        BodyRecord.objects.create(user_id=self.user.id, height=175, weight=70)
        EatingRecord.objects.create(user_id=self.user.id, meal_type='lunch', calories=600)
        SleepRecord.objects.create(user_id=self.user.id, sleep_duration=8.0)
        SportsRecord.objects.create(user_id=self.user.id, sport_type='walking', duration=45)
    
    def test_user_health_stats_authenticated(self):
        """测试认证用户获取健康统计数据"""
        request = self.factory.get('/health/user/stats/')
        request.user = self.user
        
        response = user_health_stats(request)
        
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn('bodyRecordCount', response.data)
        self.assertIn('eatingRecordCount', response.data)
        self.assertIn('sleepRecordCount', response.data)
        self.assertIn('sportsRecordCount', response.data)
        
        # 验证统计数据
        self.assertEqual(response.data['bodyRecordCount'], 1)
        self.assertEqual(response.data['eatingRecordCount'], 1)
        self.assertEqual(response.data['sleepRecordCount'], 1)
        self.assertEqual(response.data['sportsRecordCount'], 1)
    
    def test_user_yesterday_analysis_with_data(self):
        """测试有数据时的昨日健康分析"""
        # 创建昨天的健康报告
        yesterday = timezone.now().date() - timedelta(days=1)
        HealthReport.objects.create(
            user_id=self.user.id,
            file_path='',
            analysis_result='测试分析结果',
            uploaded_at=timezone.make_aware(timezone.datetime.combine(yesterday, timezone.datetime.min.time()))
        )
        
        request = self.factory.get('/health/user/yesterday-analysis/')
        request.user = self.user
        
        response = user_yesterday_analysis(request)
        
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn('analysis_result', response.data)
        self.assertIn('analysis_date', response.data)
        self.assertEqual(response.data['analysis_result'], '测试分析结果')
    
    def test_user_yesterday_analysis_no_data(self):
        """测试无数据时的昨日健康分析"""
        request = self.factory.get('/health/user/yesterday-analysis/')
        request.user = self.user
        
        response = user_yesterday_analysis(request)
        
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertIn('analysis_result', response.data)
        self.assertIn('analysis_date', response.data)


class HealthTasksTest(TestCase):
    """健康任务测试"""
    
    def setUp(self):
        self.user = User.objects.create_user(
            username='testuser',
            email='test@example.com',
            password='testpass123'
        )
    
    def test_daily_health_analysis_task_logic(self):
        """测试每日健康分析任务的逻辑"""
        from .tasks import daily_health_analysis_task
        
        # 创建昨天的健康数据
        yesterday = timezone.now().date() - timedelta(days=1)
        
        # 创建各种健康记录
        BodyRecord.objects.create(
            user_id=self.user.id,
            height=175,
            weight=70,
            created_at=timezone.make_aware(timezone.datetime.combine(yesterday, timezone.datetime.min.time()))
        )
        
        EatingRecord.objects.create(
            user_id=self.user.id,
            meal_type='dinner',
            calories=800,
            created_at=timezone.make_aware(timezone.datetime.combine(yesterday, timezone.datetime.min.time()))
        )
        
        # 验证数据创建成功
        self.assertEqual(BodyRecord.objects.filter(user_id=self.user.id).count(), 1)
        self.assertEqual(EatingRecord.objects.filter(user_id=self.user.id).count(), 1)


class HealthAPIIntegrationTest(TestCase):
    """健康API集成测试"""
    
    def setUp(self):
        self.user = User.objects.create_user(
            username='testuser',
            email='test@example.com',
            password='testpass123'
        )
        
        # 创建完整的测试数据
        for i in range(3):
            BodyRecord.objects.create(user_id=self.user.id, height=170+i, weight=65+i)
            EatingRecord.objects.create(user_id=self.user.id, meal_type=f'meal_{i}', calories=500+i*100)
            SleepRecord.objects.create(user_id=self.user.id, sleep_duration=7.0+i*0.5)
            SportsRecord.objects.create(user_id=self.user.id, sport_type=f'sport_{i}', duration=30+i*10)
    
    def test_complete_health_data_flow(self):
        """测试完整的健康数据流程"""
        # 验证数据创建
        self.assertEqual(BodyRecord.objects.filter(user_id=self.user.id).count(), 3)
        self.assertEqual(EatingRecord.objects.filter(user_id=self.user.id).count(), 3)
        self.assertEqual(SleepRecord.objects.filter(user_id=self.user.id).count(), 3)
        self.assertEqual(SportsRecord.objects.filter(user_id=self.user.id).count(), 3)
        
        # 测试健康统计API
        factory = APIRequestFactory()
        request = factory.get('/health/user/stats/')
        request.user = self.user
        
        response = user_health_stats(request)
        
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['bodyRecordCount'], 3)
        self.assertEqual(response.data['eatingRecordCount'], 3)
        self.assertEqual(response.data['sleepRecordCount'], 3)
        self.assertEqual(response.data['sportsRecordCount'], 3)